# -*- coding: utf-8 -*-
"""
@Time : 2024/2/26 2:48 PM
@Author: imamhusan
@Des: 商品模块
"""
from fastapi import APIRouter, Request, Security
from models.goods import Goods
from models.favor import ViewLog
from schemes.goods import CreateGoods, UpdateGoods, MultiUpdateGoods
from core.Response import success, fail, res_antd
from tortoise.queryset import Q
from core.Auth import verify_token

router = APIRouter(prefix='/goods')


@router.post('', description='添加商品')
async def add_goods(post: CreateGoods):
    try:
        new_goods = await Goods.create(**post.dict())
        if new_goods:
            return success(data=new_goods, msg='添加成功')
        return fail(msg='添加失败')
    except Exception as e:
        return str(e)


@router.delete('/{id}', description='删除商品')
async def del_goods(id: int):
    try:
        del_ok = await Goods.filter(pk=id).delete()
        if del_ok:
            return success(data=del_ok, msg='删除成功')
        return fail(msg='删除失败')
    except Exception as e:
        return str(e)


@router.put('/{id}/{state}', description='修改商品状态', tags=['修改商品状态'])
async def update_state(id: int, state: int):
    try:
        update_ok = await Goods.filter(pk=id).update(state=state)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.put('/multi_update', description='批量修改商品状态', tags=['批量修改商品状态'])
async def multi_update(post: MultiUpdateGoods):
    try:
        update_ok = await Goods.filter(id__in=post.ids).update(state=post.state)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.put('/{id}', description='修改商品')
async def update_goods(id: int, post: UpdateGoods):
    try:
        data = post.dict()
        update_ok = await Goods.filter(pk=id).update(**data)
        if update_ok:
            return success(data=update_ok, msg='修改成功')
        return fail(msg='修改失败')
    except Exception as e:
        return str(e)


@router.get('', description='商品列表', dependencies=[Security(verify_token)])
async def get_goods(req: Request, type_id: int = None, keyword: str = None, pageSize: int = 8, current: int = 1):
    try:
        lan = req.headers.get('lan', 'uy')
        device = req.headers.get('device', 'mp')
        where = {"state__not": -1}
        if type_id:
            where['type_id'] = type_id
        query = Q()
        if keyword:
            query = Q(title_uy__contains=keyword) | Q(title_ch__contains=keyword)

        if device != 'web':
            goods_list = await Goods.filter(query, **where).values('id', 'image', 'price', 'views', 'quantity', title=f'title_{lan}')
            return success(data=goods_list, msg='获取成功')
        else:
            query = Goods.filter(query, **where)
            total = await query.count()
            goods_list = await query.offset(pageSize * (current - 1)).limit(pageSize).order_by('-id').values()
            return res_antd(data=goods_list, total=total)
    except Exception as e:
        return str(e)


@router.get('/{id}', description='商品信息', dependencies=[Security(verify_token)])
async def get_goods(req: Request, id: int):
    try:
        lan = req.headers.get('lan', 'uy')
        device = req.headers.get('device', 'mp')

        if device != 'web':
            user_id = req.state.user_id
            # 记录观看商品
            await ViewLog.update_or_create(user_id=user_id, goods_id=id)

            goods = await Goods.get_or_none(pk=id).select_related('favors')
            goods.views += 1
            await goods.save()
            goods_dict = goods.to_dict(lan=lan)
            goods['favor'] = await goods.favors.filter(goods_id=id).first().values_list('state', flat=True) or 0
            return success(data=goods_dict, msg='获取成功')
        else:
            goods = await Goods.get_or_none(pk=id)
            return res_antd(data=goods)
    except Exception as e:
        return str(e)

